<?php
declare(strict_types=1);

namespace App\Utils\Other\Gos;

use App\Exception\InternalException;
use App\Utils\Http\Request;
use Hyperf\Collection\Arr;
use Hyperf\Context\Context;
use function Hyperf\Support\make;

Class App {

    /**
     * 域名
     * @var string
     */
    protected string $domain = 'https://gos.api.61can.com/';

    /**
     * 设置配置
     * @param array $config
     */
    public function setConfig(array $config):static
    {
        $configArr = $this->getConfig();
        if ($configArr) {
            $config = array_merge($configArr, $config);
        }
        Context::set(static::class, $config);

        return $this;
    }

    /**
     * 返回配置信息
     * @return mixed
     */
    public function getConfig($key=null)
    {
        $config = Context::get(static::class);
        return $key?Arr::get($config, $key):$config;
    }

    /**
     * 设置路径
     * @param string $path
     * @return $this
     */
    protected function setPath(string $path):static
    {
        $this->setConfig(['path'=>$path]);
        return $this;
    }

    /**
     * 获取当前路径
     * @return string
     */
    protected function getPath():string
    {
        return $this->getConfig('path')?:'';
    }

    /**
     * 请求
     * @param array $params
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function request(array $params=[])
    {
        /** @var Request $http */
        $http = make(Request::class);
        $response = json_decode($http->post($this->domain.$this->getPath(), $params, true), true);
        logs(json_encode($response, JSON_UNESCAPED_UNICODE));

        return $this->response($response);
    }

    /**
     * 响应
     * @param $response
     * @param array $params
     * @return mixed
     */
    protected function response($response)
    {
        if (!isset($response['code']) || $response['code'] !== 200) {
            $message = Arr::get($response, 'message');
            throw new InternalException($message?:'response is null');
        }

        return $response['data'];
    }
}